package day04;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Jetwang
 * @version 1.0
 * @since 2023/3/15 18:35
 * 数组中出现次数超过一半的数字
 */
public class Offer39 {
    public static int majorityElement(int[] nums) {
        // 采用hashmap
        /*Map<Integer, Integer> map = new HashMap<>();
        int half = (int) Math.ceil(nums.length / 2.0);
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            if (map.containsKey(num)) {
                map.put(num, map.get(num) + 1);
            } else {
                map.put(num, 1);
            }
        }
        Set<Integer> set = map.keySet();
        for (Integer res : set) {
            if (map.get(res) >= half) {
                return res;
            }
        }
        return -1;*/

        // 对拼消耗法
        int candidate = 0;
        int sum = 0;

        for (int num : nums) {
            if (sum == 0) {
                candidate = num;
            }
            if (candidate == num) {
                sum++;
            } else {
                sum--;
            }
        }
        return candidate;
    }

    public static void main(String[] args) {
        System.out.println(majorityElement(new int[]{1, 2, 3, 2, 2, 2, 5, 4, 2}));
    }
}
